package org.example.spring_blog.utils;

import org.springframework.context.annotation.Configuration;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Configuration
public class SecurityUtils {
    /**
     * 加密
     * @param password 用户注册时的密码
     * @return 盐值+md5加密
     */
    public static String encrypt(String password){
        //通过UUID生成随机盐值并去掉“-”
        String salt = UUID.randomUUID().toString().replace("-","");

        //md5加密
        String finalPassword = DigestUtils.md5DigestAsHex((password + salt).getBytes());

        return salt + finalPassword;
    }

    /**
     *验证密码
     * @param inputPassword 用户输入的密码
     * @param sqlPassword 数据库记录的密码，是通过上面的encrypt加密后的密码
     * @return
     */
    public static boolean verify(String inputPassword, String sqlPassword){
        if(!StringUtils.hasLength(inputPassword)){
            return false;
        }
        if (sqlPassword == null || sqlPassword.length() != 64){
            return false;
        }

        String salt = sqlPassword.substring(0,32);
        String finalPassword = DigestUtils.md5DigestAsHex((inputPassword + salt).getBytes());

        return (salt + finalPassword).equals(sqlPassword);

    }

}
